package com.shunwang.htmlparser.parser;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.jsoup.nodes.Element;

import com.shunwang.htmlparser.pojo.DoubleColor;

public class DoubleColorParser implements DocumentCollectionParser<DoubleColor> {

	@Override
	public List<DoubleColor> parser(Element targetElement) {
		Element ele =  targetElement.child(0);
		if(ele != null && ele.tagName().equals("tbody") && ele.children().size() > 0){
			List<DoubleColor> doubles = new ArrayList<DoubleColor>();
			for(Element info:ele.children()){
				if(info.tagName().equals("tr") && info.children().size()> 0){
					String date =null;
					String sno = null;
					String number = null;
					for(int i=0,len=info.children().size();i<len;i++){
						Element td = info.child(i);
						
						if(td.tagName().equals("td")){
							if(i==0){
								date = getDate(td);
								if(date == null){
									break;
								}
							}else if(i == 1){
								sno = getSno(td);
								if(sno == null){
									break;
								}
							}else if(i==2){
								number = getNumber(td);
								if(number == null){
									break;
								}else{
									DoubleColor color = buildPojo(date,sno,number);
									doubles.add(color);
								}
							}
						}
					}
				}
			}
			return doubles;
		}
		return null;
		
	}

	private DoubleColor buildPojo(String date, String sno, String number) {
		
		try {
			SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日");
			Date day = format.parse(date);
			String[] args = number.split(",");
			if(args.length != 6){
				return null;
			}
			String[] bule = args[5].split("\\+");
			if(bule.length != 2){
				return null;
			}
			DoubleColor color = new DoubleColor();
			color.setDay(day);
			color.setSno(Integer.valueOf(sno));
			color.setRed_1(Integer.valueOf(args[0].trim()));
			color.setRed_2(Integer.valueOf(args[1].trim()));
			color.setRed_3(Integer.valueOf(args[2].trim()));
			color.setRed_4(Integer.valueOf(args[3].trim()));
			color.setRed_5(Integer.valueOf(args[4].trim()));
			color.setRed_6(Integer.valueOf(bule[0].trim()));
			color.setBlue_1(Integer.valueOf(bule[1].trim()));
			return color;
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}

	private String getNumber(Element info) {
		if(info != null){
			return info.text();
		}
		return null;
	}

	private String getSno(Element info) {
		if(info != null){
			return info.text();
		}
		return null;
	}

	private String getDate(Element info) {
		if(info != null && info.child(0) != null){
			Element a = info.child(0);
			if(a.tagName().equals("a")){
				return a.text();
			}
		}
		return null;
	}

}
